# -*- coding: utf-8 -*-
import base64
import urllib

import requests
import json
from datetime import datetime

from collections import OrderedDict
from django.conf import settings
from Crypto.Hash import MD5
from Crypto.Signature import PKCS1_v1_5 as sign_pkcs1_v1_5
from Crypto.PublicKey import RSA

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import SignError, NotPayOrderError, ProcessedPayOrderError, NotResponsePayIdError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    # 正式
    '108226950220': {
        'pri_key': """
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC2AVjpuujbXIA0
+85Ip00rCkA3TSAPlJ5jieBaU6MYTbRjAJ46hStc93Qz4UTSnU3tQa8uNdVn5ifN
QZYMGJSMElmVzbW7bDL2+xuUy0jgFq9WoZDxk4Z9hZA5cslT1aaKMh7SDf8S2whp
UfwqcW4qtMuEXEnnj+xfQz8soC/Mc3zU+uAFeiGU8PO/qT007kV/JxqdRAnDwrup
ShEQBCfWbs3BVpcjbHaO+l7I/iEqGwbPPMEIAYyk9RZ1JCQ6PJw0zB5/S5jvV0Kh
3uFxXFmRrlUBUuTaTBiUryZjCGBOB5lk+bFMb3nZJcEyHds+9eNkbV2yShLEyD/F
rkbA9DqrAgMBAAECggEBAJpVeCTydsSUoq7LG7hmDbzCe4OpZddwagL0Bofxxio0
shMFkicDh6rUtvfLPQXvmAXpHfhsc+Mfun6F8AufyE8ivE6YWlNsw6bFdjTtUIWd
Ft+6L2N6ep/z40GjwW7Si99B8vqiHbrKe0570/3Vo9qY5r79VzoBxClfp7FawE13
66QnjES3ueA8IN20cI69oK7dVKP/5W8ULnRIE0ChgNcnH3vfO+tBOLd5S7iN4VZ9
fSJaGcsBckyGnyJu9ac3uqNTOG/hKuyMrXJSoHSmPw2fnAIiahtU3YbYi4FUz49X
7DLdg5mmCe+xXssYtz55wVfxJpUDahwaVC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MtI4BavVqGQ8ZOGfYWQOXLJU9WmijIe0g3/EtsIaVH8KnFu
KrTLhFxJ54/sX0M/LKAvzHN81PrgBXohlPDzv6k9NO5FfycanUQJw8K7qUoREAQn
1m7NwVaXI2x2jvpeyP4hKhsGzzzBCAGMpPUWdSQkOjycNMwef0uY71dCod7hcVxZ
ka5VAVLk2kwYlK8mYwhgTgeZZPmxTG952SXBMh3bPvXjZG1dskoSxMg/xa5GwPQ6
qwIDAQAB
""",
        'sys_pub_key': """
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAskiqaH9S1E0YXRzK1YTD
3Z9I2WPrTo7ZrEVHRYT4tzbePCVJLl+TAG74ZmTt+LKWZhkyl+F42lrUxaZRYsIz
8uPxEsd5mfJC8hEGHB8bIlPLBFhXfl86vzd69HVhwub54c96AklmSuLMRlCNused
f4nFDDbkOApniZIPMbJjvyfzHk39r0GRaXKItByi9x1bT2yb7Jts1k/K5NVtnf6A
C4acO5EqxAUPon5Jkn6gsPQCQT+RV+5kRdjDai+HYu7UpdHn7u5pdgV5r5pkcpIu
kqlUFE+LTIXtngLkKVz9bqVfJdl8LG/QgS8TbZgbi+LFYdk3bnZVfNlBu9c3c0Hm
JwIDAQAB
""",
        # 正式地址
        'gateway': 'https://gateway.xbvnnn.top/api/v0.1/Deposit/Order',
        'query_gateway': 'https://gateway.xbvnnn.top/api/v0.1/Deposit/Query',
    },
    # test
    '108056332653': {
        'pri_key': """
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDH63+P/OfZrEE3
T/sLOcA+EJ1C8JeXxfywNTqWNeg0O8oHaBL5jih60MfP8B5ajPAy/WHqA18o/by6
dq5JU8pUmV6O1hoVLPUPOeBpNA3K6P4xIopmBe8aKFmikGJ4KUlagN8avVs1FaRy
Fo8Am4B4ejUT7KE8PSxxX7IdnwPNG6P+tEn7Xev8Du9FTdeAiVL5MmQv3CKlPSf2
H4jWQkFP7ar5uNjYa6WL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QYv29W9pMF1nL
gtUqDlgdgqXZlSMKcGg4jIK9x3Nd0CrbhzXOUlt3zCz0zh7/1kq45S2ZRsudYW/G
EK+vgmFXsy7VjfBJdFmT65Ne3duzoZAUdGfR9yECgYEAhUR+lH3WrHTJ+vYb2pjy
sEUeNVCeWqjq3n+VA1WZwtcaHMHPZbvfA2NeD85g3NkYur5y8uRppG0a1g7538OT
g/Uo5BMAnqlAOxt/eRy+erYEnk3XWwVuV2gjPAftgBgNFSczC0kItKHKNZaNi4dx
2JhqIk2TEmDSesBCYNdncWY=
""",
        'sys_pub_key': """
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkbCrpm4OUfPoYxCb0UK8
2I58jPZFliLCfYpySUTITylHlNMz1vBsIix+pmrOHXE1oEy71shZKtXyLmkawRrH
fcUJxlGrO4JMWWHvva64JIM1hxccXF9ZanSRLaxB0ObSzWpI6LVer8C8x+xU9ccN
WadMcYQ/vKEWKLkJNeDJ523V/4mfJpQBESYKcRh2x61u6asAcO1ReQKdMaM3l/MU
TRzN3E0y4fVJXtuEz+iseI7q5gCdDgyUmboNeH0+iTcydE1+Zvq/7vyKFewpScPU
iPHhD1N2yueWKt3+bgiZ1ukmwywcZIAdRlZ3wWNWe8o5kmcmwon7u8dOlGdUCK9H
UwIDAQAB
""",
        # 测试地址
        'gateway': 'https://gateway.inpay.app/api/v0.1/Deposit/Order',
        'query_gateway': 'https://gateway.inpay.app/api/v0.1/Deposit/Query',
    }
}


def _get_pay_type(service):
    if service == 'alipay':  # 支付宝（扫码）
        return '1101'
    else:
        return '1101'


# 私钥
def _get_pri_key(mch_id):
    return APP_CONF[mch_id]['pri_key']


# 公钥
def _get_pub_key(mch_id):
    return APP_CONF[mch_id]['pub_key']


# 系统(通道)公钥
def _get_sys_pub_key(mch_id):
    return APP_CONF[mch_id]['sys_pub_key']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


# 加签
def rsa_sign(data, pri_key):
    key_bytes = base64.b64decode(pri_key)
    pri = RSA.importKey(key_bytes)
    cipher = MD5.new(data)
    sign = base64.b64encode(sign_pkcs1_v1_5.new(pri).sign(cipher))
    return sign


# 验签
def rsa_verify(sign, message, pub_key):
    key_bytes = base64.b64decode(pub_key)
    pub = RSA.importKey(key_bytes)
    cipher = MD5.new(message)
    t = sign_pkcs1_v1_5.new(pub).verify(cipher, base64.b64decode(urllib.unquote(sign)))
    if not t:
        _LOGGER.info("toppay sign not pass")
        raise SignError('toppay sign not pass')


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 签名字符串(下单,查询）
def url_encode(parameter):
    s = ''
    for k, v in sorted(parameter.iteritems()):
        s += '%s=%s&' % (k, v)
    return s[:-1]


# 创建支付订单
def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('brandNo', str(app_id)),
        ('orderNo', str(pay.id)),  # 订单编号
        ('price', '%.2f' % pay_amount),  # 交易金额元
        ('serviceType', _get_pay_type(service)),
        ('userName', str(pay.id)),
        ('clientIP', _get_device_ip(info)),
    ))
    parameter_dict['signature'] = rsa_sign(url_encode(parameter_dict), _get_pri_key(app_id))
    # 不参与签名字段
    parameter_dict['callbackUrl'] = '{}/pay/api/{}/toppay/{}'.format(
        settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)
    parameter_dict['frontUrl'] = ''
    parameter_dict['signType'] = 'RSA-S'

    json_data = json.dumps(parameter_dict)
    _LOGGER.info('toppay create data:%s' % json_data)
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_gateway(app_id), data=json_data, headers=headers, timeout=5)
    response_data = json.loads(response.text)
    _LOGGER.info('toppay response data:%s', response_data)
    if response_data['isSuccess']:
        data = response_data['data']
        url = data['payUrl']
        _LOGGER.info('toppay response url: %s', url)
        return {'charge_info': url}
    return {'charge_info': response_data['message']}


def str_datetime(str_time):
    s_time = str_time[:str_time.rindex('.')]
    return datetime.strptime(s_time, '%Y-%m-%d %H:%M:%S').strftime('%Y%m%d%H%M%S')


# 签名字符串(回调)
def url_encode_notify(parameter):
    parameter.pop('code')
    parameter.pop('message')
    parameter.pop('signature')
    parameter.pop('ciphertext')
    parameter['dealTime'] = str_datetime(parameter['dealTime'])
    parameter['orderTime'] = str_datetime(parameter['orderTime'])
    s = ''
    for k, v in sorted(parameter.iteritems()):
        s += '%s=%s&' % (k, v)
    _LOGGER.info('sign string:%s' % s[:-1])
    return s[:-1]


# OK
def check_notify_sign(request, app_id):
    _LOGGER.info("toppay notify body: %s,%s", request.body, type(request.body))
    data = json.loads(request.body)
    rsa_verify(data['signature'], url_encode_notify(data), _get_sys_pub_key(app_id))

    _LOGGER.info("toppay notify data: %s, order_id is: %s", data, data['orderNo'])
    pay_id = data['orderNo']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("toppay fatal error, out_trade_no not exists, data: %s", data)
        raise NotResponsePayIdError('toppay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise NotPayOrderError('toppay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ProcessedPayOrderError('toppay pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = data['orderStatus']
    trade_no = data['orderNo']
    total_fee = float(data['actualPrice'])  # 单位元
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }

    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 1:
        _LOGGER.info('toppay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)
    _LOGGER.info('toppay notify success,but not pay success,error orderStatus:%s' % trade_status)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    parameter_dict = OrderedDict((
        ('brandNo', str(app_id)),
        ('orderNo', str(pay_id)),  # 订单编号
    ))
    parameter_dict['signature'] = rsa_sign(url_encode(parameter_dict), _get_pri_key(app_id))
    parameter_dict['signType'] = 'RSA-S'  # 不参与签名
    json_parameter = json.dumps(parameter_dict)
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_query_gateway(app_id), data=json_parameter, headers=headers, timeout=5)
    response_data = json.loads(response.text)
    _LOGGER.info('toppay query response data: %s', response_data)
    if response_data['isSuccess']:
        data = response_data['data']

        trade_status = data['orderStatus']
        total_fee = float(data['actualPrice'])  # 实际交易金额(元)
        trade_no = data['orderNo']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee,
        }
        check_channel_order(pay_id, total_fee, app_id)
        # 1：交易成功
        if trade_status == 1:
            _LOGGER.info('toppay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, trade_no))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
        else:
            _LOGGER.info('toppay query order success, but not pay success, pay pay_id: %s,trade_status:%s'
                         % (trade_no, trade_status))
    else:
        _LOGGER.warn('toppay query error message: %s', response_data['message'])
